<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class CartController extends Controller
{
    public function add(Request $request)
    {
      // 提取信息
      $data = $request->except('_token');

      
      // 检测商品是否存在购物车中
      $status = $this->checkGoodsExists($data['id']);
       
        if(!$status){
          // 如果商品不存在将商品压入到session中
          $request->session()->push('user.cart',$data);
       }

          // dd(session('user.cart'));
          return view('home.cart.remind');
       
  }


  // 读取当前用的session的购物车信息
  public function index(Request $request)
  {

    $carts = $request->session()->get('user.cart');
    
    // 读取商品信息

        if(!empty($carts)){
        foreach($carts as $k=>$v)
        {
          if($v['id'] > 120){
            $carts[$k]['info'] = DB::table('shop_active')->where('id',$v['id'])->first();
            // 读取图片信息
            $carts[$k]['img'] = DB::table('shop_activepics')->where('aid',$v['id'])->first();
          }else{
            $carts[$k]['info'] = DB::table('shop_goods')->where('id',$v['id'])->first();
            // 读取图片信息
            $carts[$k]['img'] = DB::table('shop_goopics')->where('goods_id',$v['id'])->first();
          }
        }
        // dd($carts);
        // 解析模板分配变
        // dd($carts);
        return view('home.cart.index',['carts'=>$carts]);
      }
  }
  // 删除购物车
  public function delete(Request $request)
  {   
      $id = $request->id;
      foreach(session('user.cart') as $k=>$v)
      {   
          if($v['id'] == $id){
              $res = $request->session()->flush();
          }
      }
        if($res == null){
          echo '1';
        }else{
          echo '2';
        }
  }

  private function checkGoodsExists($id)
  {    
            $carts = \Session::get('user.cart'); 
            if(empty($carts)) return false; 
            // dd($carts);        
            //检测 session中是否有重复的商品 用商品的id来检测
            foreach($carts as $k => $v){
                
               if( $v['id'] == $id ){
                        return true;
                 }
            }
             return false;
  }


}
